package com.jt.shop.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by he on 2015/9/5.
 */

public class LoginInterceptor implements HandlerInterceptor  {

    private static final Logger log = LoggerFactory.getLogger(LoginInterceptor.class);

    Pattern pattern = Pattern.compile("/user|/admin|/address");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        Matcher matcher = pattern.matcher(requestURI);
        log.info("请求uri {}", requestURI);
        if (matcher.find()) {
            HttpSession session = request.getSession();
            Object loginUser = session.getAttribute("loginUser");
            log.info("登陆用户 {}", loginUser);
            if (loginUser == null) {
                log.info("没有登陆");
                response.sendRedirect("/login");
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
